#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#define BUF_SIZE 1024
void error_handling(char *message);
//判断fclose是否是半关闭
int main(int argc,char *argv[])
{
	int serv_sock,clnt_sock;
	FILE *readfp;
	FILE *writefp;
	struct sockaddr_in serv_adr,clnt_adr;
	socklen_t clnt_adr_sz;
	char buf[BUF_SIZE]={0,};
	serv_sock=socket(PF_INET,SOCK_STREAM,0);
	memset(&serv_adr,0,sizeof(serv_adr));
	serv_adr.sin_family=AF_INET;
	serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
	serv_adr.sin_port=htons(atoi(argv[1]));
	if(bind(serv_sock,(struct sockaddr*)&serv_adr,sizeof(serv_adr))==-1)
		error_handling("bind() error");
	if(listen(serv_sock,5)==-1)
		error_handling("listen() error");
	clnt_adr_sz=sizeof(clnt_adr);
	clnt_sock=accept(serv_sock,(struct sockaddr*)&clnt_adr,&clnt_adr_sz);
	
	readfp=fdopen(clnt_sock,"r");
	writefp=fdopen(clnt_sock,"w");
	fputs("FROM SERVER:Hi~ client?\n",writefp);//向客户端写入数据
	fputs("I love all of the world\n",writefp);
	fputs("You are awesome!\n",writefp);
	fflush(writefp);//将缓冲中数据刷新并删除，结束向客户端写入数据
	
	fclose(writefp);//关闭，向客户端发送EOF，告知客户端
	fgets(buf,sizeof(buf),readfp);//接收客户端发来的信息，但是因为fclose是全关闭，此时接收不到来自客户端的信息
	fputs(buf,stdout);
	fclose(readfp);
	return 0;
}
void error_handling(char *message)
{
	fputs(message,stderr);
	fputc('\n',stderr);
	exit(1);
}
